<template>
  <a-layout>
    <a-layout-content
      :style="{
        background: '#fff',
        padding: '24px',
        margin: 0,
        minHeight: '280px',
      }"
    >
      <a-input-search
        v-model:value="searchValue"
        placeholder="vue"
        enter-button
        @search="handlerSearch"
        style="width: 200px; margin-right: 10px"
      />
      <a-button type="primary" class="addbtn" @click="showAdd">添加</a-button>
      <a-table
        :columns="columns"
        :data-source="ebooks"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.title === '封面'">
            <img
              :src="column.cover ?? '/images/cover1.png'"
              alt="avatar"
              style="width: 40px; height: 40px"
            />
          </template>
          <template v-if="column.title === '分类'">
            {{ catesToObj[record.category1_id] }}/{{
              catesToObj[record.category2_id]
            }}
          </template>
          <template v-if="column.title === '描述'">
            <div class="desc" :title="record.description">
              {{ record.description }}
            </div>
          </template>
          <template v-if="column.title === 'Action'">
            <a-space size="small">
              <a-button type="primary" @click="handlerDoc(record)"
                >文档管理</a-button
              >
              <a-button type="primary" @click="showEdit(record)">
                编辑
              </a-button>
              <a-popconfirm
                title="确定删除该书籍？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="confirm($event, record.id)"
              >
                <a-button type="primary" danger> 删除 </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>

  <!-- modal -->
  <a-modal v-model:visible="visible" :title="modalTitle" @ok="handleEdit_Add">
    <a-form
      :model="formState"
      name="basic"
      :rules="rules"
      :labelCol="{ span: 4 }"
      autocomplete="off"
    >
      <a-form-item label="封面" name="cover">
        <a-input v-model:value="formState.cover" />
      </a-form-item>
      <a-form-item label="名称" name="name">
        <a-input v-model:value="formState.name" />
      </a-form-item>
      <a-form-item label="分类" name="selectCate">
        <a-cascader
          :field-names="{ label: 'name', value: 'id', children: 'children' }"
          v-model:value="formState.selectCate"
          :options="cates"
          placeholder="Please select"
          @change="handlerSelect"
        />
      </a-form-item>
      <a-form-item label="描述信息" name="description">
        <a-input v-model:value="formState.description" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, computed } from "vue";
import { getEbookListByPage, removeEbook, editEbook } from "@/api/ebooks";
import { getCategoryAllList } from "@/api/cate";
import { toTree } from "@/util/toTree";
import { message, CascaderProps } from "ant-design-vue";
import { Form } from "ant-design-vue";
import router from "@/router";

const useForm = Form.useForm;
let ebooks = reactive<any[]>([]);
let pagination = reactive({
  current: 1,
  pageSize: 5,
  total: 0,
});

let loading = ref(false);

interface Cate {
  id: number;
  name: string;
  parent: number;
  sort: number;
}
let origin_cates: any = [];
const cates: CascaderProps["options"] = reactive<Cate[]>([
  //  id: number;
  // name: string;
  // parent: number;
  // sort: number;
  // children?: Cate[];
]);

interface Column {
  title: string;
  dataIndex: string;
}
let columns: Column[] = [
  {
    title: "封面",
    dataIndex: "cover",
  },
  {
    title: "名称",
    dataIndex: "name",
  },
  {
    title: "分类",
    dataIndex: "category_id",
  },
  {
    title: "文档数",
    dataIndex: "doc_count",
  },
  {
    title: "阅读数",
    dataIndex: "view_count",
  },
  {
    title: "点赞数",
    dataIndex: "vote_count",
  },
  {
    title: "描述",
    dataIndex: "description",
  },
  {
    title: "Action",
    dataIndex: "action",
  },
];

const searchValue = ref<string>();

// 请求分页数据
const handleQuery = (params: any) => {
  loading.value = true;
  getEbookListByPage(params).then((res) => {
    loading.value = false;
    // 书本数据
    ebooks.length = 0;
    ebooks.push(...res.data.data.list);
    pagination.total = res.data.data.total;

    //重置分页按钮
    pagination.current = params.page;
  });
};
// 分类数据（下拉）
const hadlerQueryCates = () => {
  getCategoryAllList().then((res) => {
    // 分类数据
    cates.length = 0;
    let cateTree = toTree(res.data.data);
    // cates.push(...cateTree);
    // 只保存有孩子的
    cateTree.forEach((item) => {
      item.children && cates.push(item);
    });

    // 保存原始的cates
    origin_cates = res.data.data;
  });
};
// 切换页码
const handleTableChange = (pagination: any) => {
  handleQuery({
    page: pagination.current,
    size: pagination.pageSize,
  });
};

//  ========================== 删除模块 ==========================
const confirm = (e: MouseEvent, id: number) => {
  // 删除请求
  removeEbook(id).then((res) => {
    if (res.data.code == 10001) {
      message.success("删除成功");

      if (pagination.total % pagination.pageSize == 1) {
        pagination.current > 0 && pagination.current--;
      }
      // 刷新页面
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize,
      });
    } else {
      message.error("删除失败,请稍后重试");
    }
  });
};

//  ========================== 编辑 | 添加模块 ==========================
const modalTitle = ref<string>("");
const visible = ref<boolean>(false);
let formState = reactive<any>({
  id: 0,
  cover: "",
  name: "",
  selectCate: [],
  category1_id: "",
  category2_id: "",
  description: "",
});
const rules = reactive({
  name: [{ required: true, message: "不为空", trigger: ["blur", "change"] }],
  selectCate: [
    { required: true, message: "不为空", trigger: ["blur", "change"] },
  ],
  description: [
    { required: true, message: "不为空", trigger: ["blur", "change"] },
  ],
});

// 验证
const { resetFields, validate, clearValidate } = useForm(formState, rules);

//  ========================== 修改 ==========================
const showEdit = (record: any) => {
  modalTitle.value = "电子书编辑";
  visible.value = true;
  // 赋值
  Object.keys(formState).forEach((key) => {
    if (key !== "selectCate") formState[key] = record[key];
  });
  // 有二级才加上二级id
  if (formState.category2_id !== 0) {
    formState.selectCate = [formState.category1_id, formState.category2_id];
  }
};

// 改变下来菜单
const handlerSelect = (value: number[]) => {
  formState.category1_id = value[0];
  formState.category2_id = value[1];
};

//  ========================== 增加 ==========================
const showAdd = () => {
  visible.value = true;
  modalTitle.value = "添加电子书";
  // 重置数据
  resetFields();
};

//  ========================== 增加 / 编辑 ==========================
const handleEdit_Add = () => {
  validate()
    .then(() => {
      editEbook(formState).then((res) => {
        if (res.data.code === 10001) {
          message.success("编辑成功");
          // 刷新
          handleQuery({
            page: pagination.current,
            size: pagination.pageSize,
          });
          // 关闭
          visible.value = false;
          return;
        }
        message.success("编辑失败");
      });
    })
    .catch((err) => {
      alert("表单填写错误");
    });
};

//  ========================== 查询
const handlerSearch = () => {
  handleQuery({
    page: pagination.current,
    size: pagination.pageSize,
    name: searchValue.value,
  });
};

//  ========================= 文档管理
const handlerDoc = (record: any) => {
  router.push(`/doc/${record.id}`);
};

onMounted(() => {
  handleQuery({
    page: pagination.current,
    size: pagination.pageSize,
  });
});
// Created
hadlerQueryCates();

const catesToObj = computed(() => {
  let obj: any = {};
  origin_cates.forEach((item: any) => {
    obj[item.id] = item.name;
  });
  return obj;
});
</script>

<style scoped>
.desc {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}
.addbtn {
  margin-bottom: 10px;
}
</style>
